package zsy.test.java.util.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangshuaiyin
 * @date 2022/4/6 11:10
 */
@SuppressWarnings("ALL")
public class CASAtomicDemo {

    private AtomicInteger integer = new AtomicInteger(0);

    private int i = 0;

    public static void main(String[] args) {
        final CASAtomicDemo cas = new CASAtomicDemo();
        List<Thread> ts = new ArrayList<>(600);
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++) {
            Thread t = new Thread(() -> {
                for (int i = 0; i < 10000; i++) {
                    cas.count();
                    cas.safeCount();
                }
            });
            ts.add(t);
        }

        ts.forEach(Thread::start);

        // 等待所有线程执行完成
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(cas.i);
        System.out.println(cas.integer.get());
        System.out.println(System.currentTimeMillis() - start);
    }

    /**
     * 线程安全
     */
    private void safeCount() {
        for (; ; ) {
            int i = integer.get();
            // System.out.println("当前值：" + i);
            boolean suc = integer.compareAndSet(i, ++i);
            if (suc) {
                break;
            }
        }
    }

    /**
     * 线程不安全
     */
    private void count() {
        i++;
    }

}
